package com.ztjava.auth.validator;

import com.jfinal.core.Controller;
import com.ztjava.auth.model.AuthUser;
import com.ztjava.core.Constant;
import com.ztjava.core.base.BaseValidator;
import com.ztjava.core.utiliy.StringUtil;
import com.ztjava.ext.auth.annotation.UserController;

public class UserTokenValidator extends BaseValidator{

	@Override
	protected void validate(Controller c) {
		setShortCircuit(true);
		String portal = c.getClass().getAnnotation(UserController.class).portal().toUpperCase();
		validateRequiredString("username", Constant.MESSAGE, "请输入用户名！");
		validateRequiredString("password", Constant.MESSAGE, "请输入密码！");
		AuthUser authUser = null;
		String username = c.getPara("username","");
		if(username.indexOf("@")>-1){
			authUser = AuthUser.dao.findFirst("select * from "+AuthUser.tablename+" where portal=? and email=? order by id desc limit 1",portal,username);
		}else if(username.length()==11&&StringUtil.isNumeric(username)){
			authUser = AuthUser.dao.findFirst("select * from "+AuthUser.tablename+" where portal=? and phone=? order by id desc limit 1",portal,username);
		}else {
			authUser = AuthUser.dao.findFirst("select * from "+AuthUser.tablename+" where portal=? and username=? order by id desc limit 1",portal,username);
		}
		if(authUser==null){
			addError(Constant.MESSAGE,"用户名不正确！");
		}
		if(authUser.get("password")==null){
			addError(Constant.MESSAGE,"未设置密码，无法凭借密码登陆！");
		}
		if(authUser.getStr("enable_flag").equals(Constant.F)){
			addError(Constant.MESSAGE,"账号已被停用！");
		}
		c.setAttr("authUser", authUser);
	}

}
